<?php


namespace app\common\lib\live;


use app\common\cachemodel\live\LiveRecordingInfo;
use think\Db;
use think\Log;
use think\queue\Job;

class LiveUserLoginOrOutJob
{
    /**
     * 记录直播间用户信息
     * @param Job $job
     * @param $jobData
     */
    public function task(Job $job, $jobData)
    {
        $jobAttempts = $job->attempts();
        if ($jobAttempts > 1)
        {
            $job->delete();
            return;
        }

        try
        {
            // 获取最新的直播记录ID
            $liveRecordId = (new LiveRecordingInfo())->getNewestRecord($jobData['live_id']);
            if (!$liveRecordId)
            {
                Log::write("直播间用户进入或登出记录 直播记录ID异常「{$liveRecordId}」，数据「" . json_encode($jobData, JSON_UNESCAPED_UNICODE), 'log', true);
                $job->delete();
                return;
            }

            if ($jobData['type'] === 'login')
            {
                $res = Db::table('live_data.live_user_' . $jobData['live_id'])->where(['uid' => $jobData['uid'], 'live_record_id' => $liveRecordId, 'login_time' => $jobData['login_time']])->count();
                if (!$res)
                {
                    $d = [
                        'uid' => $jobData['uid'],
                        'live_record_id' => $liveRecordId,
                        'duration' => 0,
                        'login_time' => $jobData['login_time'],
                        'login_out_time' => 0
                    ];

                    Db::table('live_data.live_user_' . $jobData['live_id'])->insert($d);
                }
            } else
            {
                $id = Db::table('live_data.live_user_' . $jobData['live_id'])->where(['uid' => $jobData['uid'], 'live_record_id' => $liveRecordId, 'login_time' => $jobData['login_time']])->value('id');
                if ($id)
                {   // 更新记录 用户在线时长
                    Db::table('live_data.live_user_' . $jobData['live_id'])->where(['id' => $id])->update(['duration' => $jobData['duration'], 'login_out_time' => $jobData['login_out_time']]);
                } else
                {
                    $d = [
                        'uid' => $jobData['uid'],
                        'live_record_id' => $liveRecordId,
                        'duration' => $jobData['duration'],
                        'login_time' => $jobData['login_time'],
                        'login_out_time' => $jobData['login_out_time']
                    ];
                    // 写入用户在线时长 信息
                    Db::table('live_data.live_user_' . $jobData['live_id'])->insert($d);
                }
            }
        }
        catch (\Exception $e)
        {
            Log::write("直播间用户进入或登出记录失败，数据「" . json_encode($jobData, JSON_UNESCAPED_UNICODE) . "」：错误消息：{$e->getMessage()};File:{$e->getFile()};Line:{$e->getLine()}", 'error', true);
        }

        $job->delete();
    }
}
